package com.example.remotecontrol.ui.devices

import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.Spacer
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.height
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.rememberScrollState
import androidx.compose.foundation.verticalScroll
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.filled.ArrowBack
import androidx.compose.material.icons.filled.Save
import androidx.compose.material3.Button
import androidx.compose.material3.DropdownMenuItem
import androidx.compose.material3.ExperimentalMaterial3Api
import androidx.compose.material3.ExposedDropdownMenuBox
import androidx.compose.material3.ExposedDropdownMenuDefaults
import androidx.compose.material3.FloatingActionButton
import androidx.compose.material3.Icon
import androidx.compose.material3.IconButton
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.OutlinedTextField
import androidx.compose.material3.Scaffold
import androidx.compose.material3.SnackbarHost
import androidx.compose.material3.SnackbarHostState
import androidx.compose.material3.Text
import androidx.compose.material3.TopAppBar
import androidx.compose.runtime.Composable
import androidx.compose.runtime.LaunchedEffect
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.rememberCoroutineScope
import androidx.compose.runtime.setValue
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.unit.dp
import com.example.remotecontrol.data.model.Device
import com.example.remotecontrol.data.model.DeviceControlType
import com.example.remotecontrol.data.model.DeviceType
import com.example.remotecontrol.data.model.IrDeviceData
import com.example.remotecontrol.data.model.TVRemoteCode
import kotlinx.coroutines.launch

/**
 * 设备添加/编辑界面
 */
@OptIn(ExperimentalMaterial3Api::class)
@Composable
fun DeviceAddEditScreen(
    deviceId: String? = null,
    onDeviceSaved: () -> Unit,
    onNavigateBack: () -> Unit,
    viewModel: DevicesViewModel
) {
    // 根据deviceId判断是添加新设备还是编辑现有设备
    val isEditMode = deviceId != null
    
    // 设备信息状态
    var deviceName by remember { mutableStateOf("") }
    var selectedDeviceType by remember { mutableStateOf(DeviceType.TV) }
    var deviceBrand by remember { mutableStateOf("") }
    var deviceModel by remember { mutableStateOf("") }
    var deviceRoom by remember { mutableStateOf("") }
    var selectedControlType by remember { mutableStateOf(DeviceControlType.IR) }
    
    // 下拉菜单展开状态
    var expandedDeviceType by remember { mutableStateOf(false) }
    var expandedControlType by remember { mutableStateOf(false) }
    
    val snackbarHostState = remember { SnackbarHostState() }
    val coroutineScope = rememberCoroutineScope()
    
    // 如果是编辑模式，获取设备信息
    LaunchedEffect(deviceId) {
        if (isEditMode && deviceId != null) {
            val device = viewModel.getDeviceById(deviceId)
            device?.let {
                deviceName = it.name
                selectedDeviceType = it.type
                deviceBrand = it.brand
                deviceModel = it.model
                deviceRoom = it.room
                selectedControlType = it.controlType
            }
        }
    }
    
    Scaffold(
        topBar = {
            TopAppBar(
                title = { Text(if (isEditMode) "编辑设备" else "添加设备") },
                navigationIcon = {
                    IconButton(onClick = onNavigateBack) {
                        Icon(Icons.Default.ArrowBack, contentDescription = "返回")
                    }
                }
            )
        },
        floatingActionButton = {
            FloatingActionButton(
                onClick = {
                    if (validateInput(deviceName, deviceBrand)) {
                        val device = createDevice(
                            id = deviceId,
                            name = deviceName,
                            type = selectedDeviceType,
                            brand = deviceBrand,
                            model = deviceModel,
                            room = deviceRoom,
                            controlType = selectedControlType
                        )
                        viewModel.addOrUpdateDevice(device)
                        onDeviceSaved()
                    } else {
                        coroutineScope.launch {
                            snackbarHostState.showSnackbar("请填写设备名称和品牌")
                        }
                    }
                }
            ) {
                Icon(Icons.Default.Save, contentDescription = "保存")
            }
        },
        snackbarHost = { SnackbarHost(snackbarHostState) }
    ) { padding ->
        Column(
            modifier = Modifier
                .fillMaxSize()
                .padding(padding)
                .padding(16.dp)
                .verticalScroll(rememberScrollState()),
            horizontalAlignment = Alignment.CenterHorizontally
        ) {
            // 设备名称
            OutlinedTextField(
                value = deviceName,
                onValueChange = { deviceName = it },
                label = { Text("设备名称") },
                modifier = Modifier.fillMaxWidth(),
                singleLine = true
            )
            
            Spacer(modifier = Modifier.height(16.dp))
            
            // 设备类型
            ExposedDropdownMenuBox(
                expanded = expandedDeviceType,
                onExpandedChange = { expandedDeviceType = !expandedDeviceType }
            ) {
                OutlinedTextField(
                    modifier = Modifier
                        .fillMaxWidth()
                        .menuAnchor(),
                    readOnly = true,
                    value = selectedDeviceType.displayName,
                    onValueChange = {},
                    label = { Text("设备类型") },
                    trailingIcon = { ExposedDropdownMenuDefaults.TrailingIcon(expanded = expandedDeviceType) }
                )
                
                ExposedDropdownMenu(
                    expanded = expandedDeviceType,
                    onDismissRequest = { expandedDeviceType = false }
                ) {
                    DeviceType.values().forEach { type ->
                        DropdownMenuItem(
                            text = { Text(type.displayName) },
                            onClick = {
                                selectedDeviceType = type
                                expandedDeviceType = false
                            }
                        )
                    }
                }
            }
            
            Spacer(modifier = Modifier.height(16.dp))
            
            // 设备品牌
            OutlinedTextField(
                value = deviceBrand,
                onValueChange = { deviceBrand = it },
                label = { Text("设备品牌") },
                modifier = Modifier.fillMaxWidth(),
                singleLine = true
            )
            
            Spacer(modifier = Modifier.height(16.dp))
            
            // 设备型号
            OutlinedTextField(
                value = deviceModel,
                onValueChange = { deviceModel = it },
                label = { Text("设备型号 (可选)") },
                modifier = Modifier.fillMaxWidth(),
                singleLine = true
            )
            
            Spacer(modifier = Modifier.height(16.dp))
            
            // 设备房间
            OutlinedTextField(
                value = deviceRoom,
                onValueChange = { deviceRoom = it },
                label = { Text("所在房间 (可选)") },
                modifier = Modifier.fillMaxWidth(),
                singleLine = true
            )
            
            Spacer(modifier = Modifier.height(16.dp))
            
            // 控制方式
            ExposedDropdownMenuBox(
                expanded = expandedControlType,
                onExpandedChange = { expandedControlType = !expandedControlType }
            ) {
                OutlinedTextField(
                    modifier = Modifier
                        .fillMaxWidth()
                        .menuAnchor(),
                    readOnly = true,
                    value = selectedControlType.displayName,
                    onValueChange = {},
                    label = { Text("控制方式") },
                    trailingIcon = { ExposedDropdownMenuDefaults.TrailingIcon(expanded = expandedControlType) }
                )
                
                ExposedDropdownMenu(
                    expanded = expandedControlType,
                    onDismissRequest = { expandedControlType = false }
                ) {
                    DeviceControlType.values().forEach { type ->
                        DropdownMenuItem(
                            text = { Text(type.displayName) },
                            onClick = {
                                selectedControlType = type
                                expandedControlType = false
                            }
                        )
                    }
                }
            }
            
            Spacer(modifier = Modifier.height(32.dp))
            
            Button(
                onClick = {
                    if (validateInput(deviceName, deviceBrand)) {
                        val device = createDevice(
                            id = deviceId,
                            name = deviceName,
                            type = selectedDeviceType,
                            brand = deviceBrand,
                            model = deviceModel,
                            room = deviceRoom,
                            controlType = selectedControlType
                        )
                        viewModel.addOrUpdateDevice(device)
                        onDeviceSaved()
                    } else {
                        coroutineScope.launch {
                            snackbarHostState.showSnackbar("请填写设备名称和品牌")
                        }
                    }
                },
                modifier = Modifier.fillMaxWidth()
            ) {
                Text(if (isEditMode) "更新设备" else "添加设备")
            }
        }
    }
}

/**
 * 验证输入是否有效
 */
private fun validateInput(name: String, brand: String): Boolean {
    return name.isNotBlank() && brand.isNotBlank()
}

/**
 * 创建设备对象
 */
private fun createDevice(
    id: String? = null,
    name: String,
    type: DeviceType,
    brand: String,
    model: String,
    room: String,
    controlType: DeviceControlType
): Device {
    // 针对不同控制类型创建特定数据
    val irData = if (controlType == DeviceControlType.IR) {
        val addressCode = TVRemoteCode.getAddressCode(brand)
        val commandMap = TVRemoteCode.getCommandMap(brand)
        IrDeviceData(addressCode = addressCode, commandMap = commandMap)
    } else null
    
    // 使用现有ID或创建新设备
    return if (id != null) {
        Device(
            id = id,
            name = name,
            type = type,
            brand = brand,
            model = model,
            room = room,
            controlType = controlType,
            irData = irData
        )
    } else {
        Device(
            name = name,
            type = type,
            brand = brand,
            model = model,
            room = room,
            controlType = controlType,
            irData = irData
        )
    }
} 